// src/routes/users.ts
import express, { Request, Response, NextFunction } from "express";
import { Articles, Tags } from "../models/index";
import { whereParamasHandler } from "@/utils/sequelize";

const router = express.Router();

// 获取文章列表
router.get("/", async (req: Request, res: Response) => {
  try {
    const { page = 1, pageSize = 10 } = req.body;
    const where = whereParamasHandler(
      {},
      {
        page: page,
        pageSize: pageSize,
      }
    );

    const article = await Articles.findByPk(1);
    console.log("article>", article);
    if (article) {
      const tags = await article.getTags(); // 获取关联的标签
      console.log("tags>", tags);
    }

    const { rows, count } = await Articles.findAndCountAll(where);
    res.json({
      total: count,
      page: page,
      pageSize: pageSize,
      totalPages: Math.ceil(count / pageSize),
      list: rows,
    });
  } catch (error) {
    res.status(500).json({ message: "Error retrieving users", error });
  }
});

// 查询文章列表
router.post("/", async (req: Request, res: Response) => {
  try {
    const { page = 1, pageSize = 10 } = req.body;
    const where = whereParamasHandler(
      {
        title: req.body.title,
        status: req.body.status,
        category_id: req.body.category_id,
      },
      {
        page: page,
        pageSize: pageSize,
      }
    );
    console.log("where>>", where);
    const { rows, count } = await Articles.findAndCountAll(where);
    res.status(200).json({
      total: count,
      page: page,
      pageSize: pageSize,
      totalPages: Math.ceil(count / pageSize),
      list: rows,
    });
  } catch (error) {
    res.status(500).json({ message: "Error retrieving users", error });
  }
});

// 查询文章内容
router.post("/detail", async (req: Request, res: Response) => {
  try {
    const { id } = req.body;
    const acticle = await Articles.findByPk(id);
    console.log("acticle>>", acticle?.dataValues.tags);
    const result = Object.assign({}, acticle?.dataValues, {
      tags: acticle?.dataValues.tags ? acticle?.dataValues.tags : [],
    });
    res.status(200).json(result);
  } catch (error) {
    console.log("error", error);
    res.status(500).json({ message: "Error retrieving users", error });
  }
});

// 创建新文章
router.post("/add", async (req: Request, res: Response) => {
  const {
    title,
    content,
    author_id,
    category_id,
    cover_image,
    views = 0,
    status = 0,
    tags = "[]",
  } = req.body;
  let tagList = JSON.parse(tags);
  console.log(title, content, author_id, category_id, views, status);
  try {
    const articleInfo = await Articles.create({
      title,
      content,
      author_id,
      category_id,
      views,
      status,
      cover_image,
      tags: tagList,
    });
    // 关联标签
    if (tags && Array.isArray(tags)) {
      const tagInstances = await Tags.findAll({
        where: {
          id: tagList,
        },
      });
      // 将文章和标签关联
      await articleInfo.addTag(tagInstances);
    }
    res.status(201).json(articleInfo);
  } catch (error) {
    console.log("error", error);
    res.status(500).json({ message: "Error creating user", error });
  }
});

// 更改文章
router.patch("/edit", async (req: Request, res: Response) => {
  const {
    title,
    content,
    category_id,
    status,
    id,
    tags,
    cover_image = "",
  } = req.body;
  try {
    const acticle = await Articles.findByPk(id);
    if (acticle) {
      acticle.title = title;
      acticle.content = content;
      acticle.category_id = category_id;
      acticle.status = status;
      acticle.tags = tags;
      acticle.cover_image = cover_image;
      console.log(tags);
      // 关联标签
      if (tags && Array.isArray(tags)) {
        const tagInstances = await Tags.findAll({
          where: {
            id: tags,
          },
        });
        // 将文章和标签关联
        await acticle.setTags(tagInstances);
      }
      acticle.save();
      res.status(200).json({ message: "操作成功" });
    } else {
      res.status(400).json({ message: "文章不存在" });
    }
  } catch (error) {
    console.log("error", error);
    res.status(500).json({ message: "Error creating user", error });
  }
});

// 删除文章
router.delete(
  "/delete/:id",
  async (req: Request, res: Response, next: NextFunction) => {
    const { id } = req.params; // 获取要删除的文章 ID
    console.log(id, "id>>");
    try {
      if (!id) {
        res.status(400).json({ message: "参数校验失败" });
      } else {
        const where = whereParamasHandler(
          {
            id: id,
          },
          null,
          false
        );
        const deletedCount = await Articles.destroy(where);
        if (deletedCount === 0) {
          res.status(404).json({ message: "文章不存在或已删除" });
          return;
        }
        res.status(200).json({ message: "文章删除成功" });
      }
    } catch (error) {
      console.error("删除文章失败", error);
      res.status(500).json({ message: "服务器错误", error });
    }
  }
);

export default router;
